package com.itboye.ihomebank.activity.keytwo;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.base.MyApplcation;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.SIDBean;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.presenter.KeyPresenter;
import com.itboye.ihomebank.presenter.KeyTwoPresenter;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimesUtils;
import com.sitri.sdk.SLock;
import com.sitri.sdk.callback.visible.CommonCallback;
import com.sitri.sdk.model.ResultData;
import com.sitri.sdk.model.ResultError;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;

/**
 * 发送密码界面-白马锁
 */
public class SendPassActivity extends BaseOtherActivity implements Observer ,CommonCallback{
    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;
    TextView fasong_time01;
    TextView fasong_time,fasong_shixiao;// 时间
    LinearLayout xuanze_end;//结束生效时间
    TextView fasong_time02,end_time;//结束生效时间
    LinearLayout fasong_duanxin;// 短信发送
    private int type = 2;//选择的类型
    KeyTwoPresenter keyPresenter;
    String lockid,mac;
    String uid;
    long startT, endT;
    long currentTime;

    LinearLayout xuanze_shixiao,xuanze_time;
    private TimePickerView pvCustomTime,pvCustomTimeTwo;
    private OptionsPickerView pvOptions;

    String personType;// 0 管理员
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.xuanze_shixiao:
            case R.id.fasong_shixiao:// 时效
                pvOptions.show();
                break;
            case R.id.fasong_time01:
            case R.id.fasong_time:
            case R.id.xuanze_time:// 选择开始时间
                pvCustomTime.show(v);//弹出时间选择器，传递参数过去，回调的时候则可以绑定此view
                break;
            case R.id.fasong_duanxin:// 短信发送，
                if (type==1){
//                    if (year==0){
//                        ByAlert.alert("请选择密码有效期");
//                        return;
//                    }

                    Calendar calendar=Calendar.getInstance();  //获取当前时间，作为图标的名字
                    year=calendar.get(Calendar.YEAR);
                    month=calendar.get(Calendar.MONTH)+1;
                    dares=calendar.get(Calendar.DAY_OF_MONTH);

                    String tempPass = SLock.getServices().getTempPass(mac, year, month, dares);
                    logTempPass(tempPass);
                }else{
                    showProgressDialog("正在为你获取密码，请稍后...", true);
                    String sid=SPUtils.get(MyApplcation.ctx,null,SPContants.LOCK_SESSION,"")+"";

                    if ("".equals(sid)){
                        keyPresenter.onKeyboardPwd(uid, lockid, type + "", "",  "", "",String.valueOf(System.currentTimeMillis()/1000));

                    }else {
                        keyPresenter.onKeyboardPwd(sid, lockid, type + "", "",  "", "",String.valueOf(System.currentTimeMillis()/1000));

                    }
                }
                break;

            default:
                break;
        }

    }
    @Override
    protected int layout_id() {
        return R.layout.activity_send_pass;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        SLock.getServices().disconnectBle();
    }

    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("发送密码");
        SLock.getServices().setCommonCallback(this);
       // initTimePicker();
        keyPresenter = new KeyTwoPresenter(this);
        lockid = this.getIntent().getStringExtra("lockid");
        mac = this.getIntent().getStringExtra("mac");
        personType=this.getIntent().getStringExtra("type");
        getOptionData();
        initOptionPicker();
        uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";

        currentTime = System.currentTimeMillis();
    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }

    @Override
    public void update(Observable observable, Object data) {
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == keyPresenter.sendJianPanPass_success) {
                //ByAlert.alert(entity.getData());
                String type01 = "";
                if (type == 1) {
                    type01 = "单次密码";
                }
                if (type == 2) {
                    type01 = "永久密码";
                }
                String content = type01;
                Uri smsToUri = Uri.parse("smsto:");
                Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
                intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + entity.getData().toString() + "," + content);
                startActivity(intent);

            } else if (entity.getEventType() == keyPresenter.sendJianPanPass_fail) {
                if (entity.getData() instanceof ServerError ||entity.getData() instanceof TimeoutError){//服务器失败
                    //切换 锁备用服务器
                    showAlert();
                }else {
                    ByAlert.alert(entity.getData());
                }
            }else if (entity.getEventType()== UserPresenter.By_GETSID_success){//获取sid 成功
                SIDBean data1 = (SIDBean) entity.getData();
                SPUtils.put(MyApplcation.ctx,null, SPContants.LOCK_SESSION,data1.getSid());
                SPUtils.put(MyApplcation.ctx,null,SPContants.ISLOCK,true);
                toRefreshData(data1.getSid());
            }else if (entity.getEventType()==UserPresenter.By_GETSID_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }

    }

    private void toRefreshData(String sid) {
        if ("".equals(sid)){
            keyPresenter.onKeyboardPwd(uid, lockid, type + "", "",  "", "",String.valueOf(System.currentTimeMillis()/1000));

        }else {
            keyPresenter.onKeyboardPwd(sid, lockid, type + "", "",  "", "",String.valueOf(System.currentTimeMillis()/1000));

        }
    }

    int year;
    int month;
    int dares;
    /**
     * 选择开始时间
     */
    private void initTimePicker() {
        /**
         * @description
         * 注意事项：
         * 1.自定义布局中，id为 optionspicker 或者 timepicker 的布局以及其子控件必须要有，否则会报空指针.
         * 具体可参考demo 里面的两个自定义layout布局。
         * 2.因为系统Calendar的月份是从0-11的,所以如果是调用Calendar的set方法来设置时间,月份的范围也要是从0-11
         * setRangDate方法控制起始终止时间(如果不设置范围，则使用默认时间1900-2100年，此段代码可注释)
         */
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(2017, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2030, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调

                fasong_time.setText(getTime(date));
                startT = TimesUtils.getStringToDateTwo02(getTime(date));
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(date);
                year =calendar.get(Calendar.YEAR);
                month=calendar.get(Calendar.MONTH) + 1;
                dares= calendar.get(Calendar.DAY_OF_MONTH);
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                                pvCustomTime.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .setLabel("年", "月", "日", "", "", "")
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(0xFF24AD9D)
                .build();
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 00:00");
        return format.format(date);
    }
    private ArrayList<String> options1Items = new ArrayList<>();
    /**
     * 选择时效
     */
    private void initOptionPicker() {//条件选择器初始化

        /**
         * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
         */
        pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = options1Items.get(options1);

                if (options1==0){
                    type = 1;
                    fasong_shixiao.setText(options1Items.get(options1));
                   // xuanze_time.setVisibility(View.VISIBLE);
                }else if (options1==1){
                    type = 2;
                  //  xuanze_time.setVisibility(View.INVISIBLE);
                    fasong_shixiao.setText(options1Items.get(options1));
                }
            }
        })
                .setTitleText("请选择密码类型")
                .setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0, 1)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.BLACK)
                .setCancelColor(Color.BLACK)
                .setSubmitColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setLabels("", "", "")
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        pvOptions.setPicker(options1Items);//二级选择器
    }
    private void getOptionData() {
        //选项1
        if (personType.equals("0")){
            options1Items.add("单次密码");
            options1Items.add("永久密码");
        }else {
            options1Items.add("单次密码");
        }
    }
    private void logTempPass(final String log) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Uri smsToUri = Uri.parse("smsto:");
                Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);
                intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + log + ",单次密码,只限"+year+"-"+month+"-"+dares+"当天使用");
              //  intent.putExtra("sms_body", "您的住家智能锁的开锁密码为：" + log + ",单次密码,只限当天使用");
                startActivity(intent);
            }
        });
    }


    @Override
    public void onSuccess(ResultData resultData) {

    }

    @Override
    public void onFailed(ResultError resultError) {

    }
}
